<template>
  <el-form-item :label="prop.name" :prop="prop.id" :rules="rules">
    <template slot="label">
      <rva-search-config :prop="prop"></rva-search-config>
    </template>
    <el-select
      size="small"
      :value="value"
      :multiple="this.prop.formSelectorSingle == 'N'"
      filterable
      remote
      reserve-keyword
      :placeholder="'请输入' + prop.name"
      :remote-method="searchSelectOptions"
      @change="$emit('input', $event)"
      :loading="loading"
    >
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
  </el-form-item>
</template>

<script>
import request from '@/utils/request'
import {RvaUtils} from '@/api/rva/util'

export default {
  name: "RvaFormSelector",
  props: ['prop', 'value', 'formRef', 'formData', 'formItemProp'],
  data() {
    return {
      rules:[],
      options: [],
      loading: false,
      disabled: false
    }
  },
  created() {
    this.init();
  },
  methods: {
    initOptions(url, params, fn) {
      this.options = [];
      RvaUtils.clone(this.formData, params);
      if (this.prop.data && JSON.parse(this.prop.data).selectorPageSize) {
        params.pageSize = JSON.parse(this.prop.data).selectorPageSize;
      } else {
        params.pageSize = 20;
      }
      request({
        url,
        method: 'post',
        data: params
      }).then(response => {
        for (var i in response.rows) {
          let row = response.rows[i];
          row.value = row[row.keyPropId].toString();
          row.label = row[row.namePropId];
          this.options.push(row);
        }
        if (fn) {
          fn ();
        }
        // 隐藏遮罩层
        this.loading = false;
      }).catch(err => {
        console.log (url, err);
        // 隐藏遮罩层
        this.loading = false;
      });
    },
    init() {
      if (RvaUtils.isEmpty(this.value)) {
        if (this.prop.data && JSON.parse(this.prop.data).selectorInitOptions) {
          this.searchSelectOptions('#$@$#');
        }
        return;
      }
      // 显示遮罩层
      this.loading = true;
      var me = this;
      this.initOptions(this.prop.formInputorData, {
        ids: this.prop.formSelectorSingle == 'N' ? this.value.join(",") : this.value
      }, function () {
        if (RvaUtils.parseValue(me.prop.data, 'selectorInitOptions')) {
          me.searchSelectOptions('#$@$#');
        }
      });
    },
    searchSelectOptions(query) {
      if (query === '') {
        return;
      }
      // 显示遮罩层
      this.loading = true;
      if (query == '#$@$#') {
        query = '';
      }
      this.initOptions(this.prop.formInputorSearch, {
        searchContent: query
      });
    }
  }
}
</script>
